Go Swagger 使用

第一步:安装 swag 工具

打开终端,运行以下命令来安装 swag 命令行工具:

1
go get -u github.com/swaggo/swag/cmd/swag

第二步:安装 Swagger UI 中间件

为了能在浏览器中查看生成的 Swagger 文档,你需要一个 HTTP 中间件来提供 Swagger UI。这里推荐使用 gin-swagger,因为它和 Go 的 Gin 框架结合得非常好。如果你使用其他框架(如 Echo),也有对应的库。

1
2
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files # 静态文件

第三步:在代码中添加注释

swag 工具通过解析你 Go 代码中的特定注释来生成 Swagger 文档。这些注释通常放在 main 函数所在的包,或者每个 API 路由处理函数(handler)的上方。

1. 项目主文件(main.go)的注释

在你的 main.go 文件顶部,添加项目级别的 Swagger 注释。这些注释定义了 API 的基本信息,比如标题、版本、描述等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

import (
"github.com/gin-gonic/gin"
// 导入 gin-swagger 和 swagger files
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"

// 导入你生成的文档
_ "你的项目名/docs"
)

// @title 你的 API 标题
// @version 1.0
// @description 这是一个示例 API 服务器。
// @termsOfService http://swagger.io/terms/

// @contact.name API 支持
// @contact.url http://www.swagger.io/support
// @contact.email [email protected]

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host localhost:8080
// @BasePath /api/v1
func main() {
r := gin.Default()

// 注册 Swagger UI 路由
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

// 你的其他 API 路由...
r.GET("/ping", Ping)

r.Run(":8080")
}

注意:_ "你的项目名/docs" 这一行非常重要,它会导入 swag 生成的文档代码,否则 Swagger UI 将无法加载。这里的 你的项目名 应该替换成你的 Go 项目模块路径,例如 _ "github.com/yourusername/your-project/docs"

2. API 路由处理函数的注释

在每个具体的 API 路由处理函数上方,使用 swag 支持的注释来描述该接口。

1
2
3
4
5
6
7
8
9
10
11
12
// PingExample godoc
// @Summary 获取服务器状态
// @Description 获取服务器的 "pong" 响应
// @Tags 服务器状态
// @Accept json
// @Produce json
// @Success 200 {string} string "pong"
// @Failure 400 {string} string "无效请求"
// @Router /ping [get]
func Ping(c *gin.Context) {
c.JSON(200, "pong")
}

常用的注释关键字包括:

  • @Summary: 接口的简短摘要。
  • @Description: 接口的详细描述。
  • @Tags: 将接口进行分组。
  • @Accept: 可接受的请求数据类型。
  • @Produce: 返回的响应数据类型。
  • @Success: 成功响应的状态码和数据模型。
  • @Failure: 失败响应的状态码和数据模型。
  • @Param: 请求参数的描述。
  • @Router: 接口的路由路径和 HTTP 方法。

你还可以为请求和响应体定义模型(Model),并在注释中引用它们。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// User 模型
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}

// GetUser godoc
// @Summary 获取用户信息
// @Description 根据用户 ID 获取详细信息
// @Tags 用户
// @Produce json
// @Param id path int true "用户 ID"
// @Success 200 {object} User
// @Router /users/{id} [get]
func GetUser(c *gin.Context) {
// ...
}

第四步:生成 Swagger 文档

在你的项目根目录(main.go 文件所在的目录),运行 swag 命令来生成文档:

1
swag init

执行此命令后,swag 会自动解析你的 Go 代码和注释,并在项目根目录生成一个名为 docs 的目录。这个目录包含了 swagger.jsonswagger.yamldoc.go 等文件。

第五步:运行项目并查看文档

现在你可以正常运行你的 Go 项目了:

1
go run main.go

项目启动后,打开浏览器,访问 http://localhost:8080/swagger/index.html,你就能看到一个完整的 Swagger UI 页面,其中包含了所有你在代码中注释的 API 接口。

通过以上五个步骤,你就可以轻松地在 Go 项目中集成并使用 swag 来自动生成和管理 Swagger 文档了。

🎯 一、核心库介绍

库名 作用 适用框架
swaggo/swag 根据注释自动生成 Swagger JSON/YAML 任何 Go Web 框架(Gin, Echo, Fiber, Iris…)
swaggo/gin-swagger 在 Gin 中提供 Swagger UI 页面 Gin 专用
swaggo/echo-swagger Echo 专用 UI Echo
swaggo/http-swagger 原生 net/http 原生 http

🚀 我们以 Gin + swaggo/swag 为例,这是目前 Go 社区最主流的组合!


🛠️ 二、完整使用步骤(Gin 项目为例)

✅ Step 1:安装 swag 命令行工具

1
go install github.com/swaggo/swag/cmd/swag@latest

💡 确保 $GOPATH/bin 在你的 PATH 环境变量中,否则运行 swag 会报“command not found”

验证安装:

1
2
swag --version
# 输出:swag version v1.xx.x

✅ Step 2:在项目中导入 Gin Swagger 中间件

1
2
3
go get -u github.com/swaggo/swag
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files

✅ Step 3:在 main.go 或项目入口添加注释 + 初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// main.go

package main

import (
"github.com/gin-gonic/gin"
_ "your-project/docs" // ⚠️ 关键!导入 docs(自动生成的)
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
_ "github.com/swaggo/swag/example/celler/httputil" // 可选,示例
)

// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/

// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email [email protected]

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host localhost:8080
// @BasePath /api/v1

// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization

func main() {
r := gin.Default()

// Swagger UI 路由
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

// 你的业务路由
r.GET("/api/v1/hello", helloHandler)

r.Run(":8080")
}

// @Summary Get hello message
// @Description get string by ID
// @Tags example
// @Accept json
// @Produce json
// @Param id path int true "User ID"
// @Success 200 {string} string "hello world"
// @Failure 400 {object} ErrorResponse
// @Router /hello/{id} [get]
func helloHandler(c *gin.Context) {
c.JSON(200, "hello world")
}

type ErrorResponse struct {
Code int `json:"code"`
Message string `json:"message"`
}

✅ Step 4:为你的 Handler 写 Swagger 注释(重点!)

Swagger 是靠注释生成文档的,格式必须严格!

📌 常用注释标签:

1
2
3
4
5
6
7
8
9
10
// @Summary      简要描述
// @Description 详细描述
// @Tags 分组标签(如 user, order)
// @Accept 请求格式(json, xml, multipart/form-data)
// @Produce 响应格式(json, xml)
// @Param 参数名 位置 类型 是否必须 "描述" [额外 schema]
// @Success 状态码 {类型} 数据类型 "描述"
// @Failure 状态码 {类型} 数据类型 "描述"
// @Router 路径 [方法]
// @Security ApiKeyAuth

🧩 示例:带请求体、响应体、路径参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// @Summary      创建用户
// @Description 创建一个新用户
// @Tags 用户管理
// @Accept json
// @Produce json
// @Param user body UserCreateRequest true "用户信息"
// @Success 201 {object} UserResponse
// @Failure 400 {object} ErrorResponse
// @Router /users [post]
func CreateUser(c *gin.Context) {
// ...
}

type UserCreateRequest struct {
Name string `json:"name" binding:"required,min=2"`
Email string `json:"email" binding:"required,email"`
}

type UserResponse struct {
ID uint `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}

💡 结构体字段的 json tag 会自动被 Swagger 识别为字段名!


✅ Step 5:生成 Swagger 文档

在项目根目录执行:

1
swag init

✅ 自动生成以下文件:

1
2
3
4
./docs
├── docs.go
├── swagger.json
└── swagger.yaml

🔄 每次修改注释后,必须重新运行 swag init 才能更新文档!


✅ Step 6:运行项目,访问 Swagger UI

启动你的 Gin 服务:

1
go run main.go

浏览器访问:http://localhost:8080/swagger/index.html

🎉 你将看到漂亮的 Swagger UI 页面,支持:

  • 在线测试 API
  • 查看请求/响应结构
  • 下载 swagger.json
  • 自动高亮参数、模型

🧩 三、高级用法 & 技巧

1. 自定义 Swagger 页面标题、URL

1
2
3
4
5
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler,
ginSwagger.URL("http://localhost:8080/swagger/doc.json"), // 自定义 doc 地址
ginSwagger.DeepLinking(true),
ginSwagger.DocExpansion("none"),
))

2. 全局安全认证(如 JWT)

main.go 顶部添加:

1
2
3
4
// @securityDefinitions.apikey  ApiKeyAuth
// @in header
// @name Authorization
// @description JWT token: Bearer <token>

在需要认证的接口加:

1
// @Security ApiKeyAuth

3. 枚举、示例值、默认值

1
2
3
4
5
type UserCreateRequest struct {
Role string `json:"role" enums:"admin,user,guest" default:"user"`
Status int `json:"status" example:"1" default:"1"`
Tags []string `json:"tags" example:"dev,backend"`
}

4. 忽略某些文件/目录

1
swag init --exclude ./internal,./cmd

5. 支持嵌套路由/分组

1
2
3
4
v1 := r.Group("/api/v1")
{
v1.GET("/users", GetUsers) // 注释照常写
}

✅ 四、最佳实践建议

  1. 注释写在 Handler 函数上方,紧贴函数定义
  2. 结构体字段用 json tag,Swagger 会自动识别
  3. 每次改注释后必须 swag init,否则不更新!
  4. 生产环境可关闭 Swagger UI
1
2
3
if os.Getenv("ENV") != "production" {
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
}
  1. 使用 @Tags 分组,让文档结构清晰
  2. 定义通用响应结构,避免重复写 {object} ErrorResponse

🚫 五、常见问题 & 解决

swag init 报错:ParseComment error

  • 检查注释格式是否正确(如 @Param 参数个数)
  • 检查结构体是否在同一个包或已导入
  • 使用 swag init -g main.go 指定入口文件

❓ 访问 /swagger/index.html 404

  • 确保 import _ "your-project/docs" 已添加
  • 确保 swag init 成功生成了 docs/ 目录
  • 检查路由是否正确:r.GET("/swagger/*any", ...)

❓ 结构体没显示在文档里?

  • 确保结构体被某个 @Success@Param 引用
  • 或手动在注释中引用:
1
// @Success 200 {object} UserResponse "成功"

🎯 六、总结

步骤 命令 / 操作 说明
1️⃣ 安装 go install github.com/swaggo/swag/cmd/swag@latest 安装 CLI 工具
2️⃣ 导入 import _ "your-project/docs" 导入自动生成的文档
3️⃣ 写注释 在 Handler 上写 // @Summary ... 核心!文档靠注释生成
4️⃣ 生成 swag init 生成 docs/swagger.json
5️⃣ 挂路由 r.GET("/swagger/*any", ginSwagger.WrapHandler(...)) 提供 UI 访问
6️⃣ 访问 http://localhost:8080/swagger/index.html 在线调试 API

🎯 一句话口诀

“swag init 生成文档,注释规范是关键,Gin 挂上 UI 路由,API 调试不再难!”

用上 Swagger 后,你的 API 文档将自动生成、实时可测、团队协作效率翻倍!🚀